﻿using AdaptPivotViewerNameSpace;
using CPokerSL.Classes;
using Pivotbrowser.Helpers;
using Pivotbrowser.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Controls.Pivot;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Pivotbrowser.Views
{
    public partial class PivotViewerGrid : UserControl
    {
        public AdaptPivotViewer AdaptPivotViewer { get; set; }
        public WrapPanel WpPopups { get; set; }
        public StackPanel SpExport { get; set; }
        public ViewModel Vm { get; set; }
        int offset { get; set; }


        public PivotViewerGrid()
        {
            InitializeComponent();
            Vm = new ViewModel();
            this.AdaptPivotViewer = this.PivotViewer;            
            this.WpPopups = this.wpPopups;
            this.SpExport = this.spExport;

            WebContext.Current.Authentication.LoggedIn += (sndr, eargs) => { this.AdaptPivotViewer.Opacity = 1; this.AdaptPivotViewer.IsHitTestVisible = true; this.WpPopups.Visibility = System.Windows.Visibility.Visible; this.SpExport.Visibility = System.Windows.Visibility.Visible; };
            WebContext.Current.Authentication.LoggedOut += (sndr, eargs) => { this.AdaptPivotViewer.Opacity = 0; this.AdaptPivotViewer.IsHitTestVisible = false; this.WpPopups.Visibility = System.Windows.Visibility.Collapsed; this.SpExport.Visibility = System.Windows.Visibility.Collapsed; };

            this.AdaptPivotViewer.ItemsSource = Vm.MinimalStudents;

            Vm.MinimalStudentsLoaded += (sender, eargs) => { if (this.refreshUri == null) UpdateFilterFromUri(HtmlPage.Document.DocumentUri); else UpdateFilterFromUri(refreshUri); };
            Vm.LoadMinimalStudents();

        }

        public PivotViewerGrid(IEnumerable isc)
        {
            InitializeComponent();
            this.AdaptPivotViewer = this.PivotViewer;
            if (isc != null)
                this.AdaptPivotViewer.ItemsSource = isc;
            this.WpPopups = this.wpPopups;
            this.SpExport = this.spExport;

            this.AdaptPivotViewer.Opacity = 1; this.AdaptPivotViewer.IsHitTestVisible = true; this.WpPopups.Visibility = System.Windows.Visibility.Visible; this.SpExport.Visibility = System.Windows.Visibility.Visible;
        }


        private void UpdateFilterFromUri(Uri uri)
        {
            if (uri.Query.Length > 0)
            {
                if (uri.Query.Contains("?filter="))
                {
                    string filter = uri.Query.Substring(8, uri.Query.Length - 8);
                    this.PivotViewer.Filter = filter;
                }
            }
        }

        private void PivotViewer_ItemDoubleClick_1(object sender, System.Windows.Controls.Pivot.PivotViewerItemDoubleClickEventArgs e)
        {
            CreateStudentPopup(e.Item);
        }

        private string FormatCSVField(object data)
        {
            string s = "";
            if (data == null)
                return s;

            if (data.GetType() == typeof(ComparableStringList))
            {
                //var converter = new ComparableStringListToStringConverter();
                //s = converter.Convert(data as ComparableStringList, null, null, null) as string;
            }
            else
                s = data.ToString();

            return String.Format("\"{0}\"",
                s.Replace("\"", "\"\"\"")
                .Replace("\n", ", ")
                .Replace("\r", "")
                );
        }

        public string ExportDataGrid(bool withHeaders, DataGrid grid)
        {
            string colPath;
            System.Reflection.PropertyInfo propInfo;
            System.Windows.Data.Binding binding;
            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            System.Collections.IList source = (grid.ItemsSource as System.Collections.IList);
            if (source == null)
                return "";

            List<string> headers = new List<string>();
            grid.Columns.ToList().ForEach(col =>
            {
                if (col is DataGridBoundColumn)
                {
                    headers.Add(FormatCSVField(col.Header.ToString()));
                }
            });
            strBuilder
            .Append(String.Join(";", headers.ToArray()))
            .Append("\r\n");

            foreach (Object data in source)
            {
                List<string> csvRow = new List<string>();
                foreach (DataGridColumn col in grid.Columns)
                {
                    if (col is DataGridBoundColumn)
                    {
                        binding = (col as DataGridBoundColumn).Binding;
                        colPath = binding.Path.Path;
                        propInfo = data.GetType().GetProperty(colPath);
                        if (propInfo != null)
                        {
                            csvRow.Add(FormatCSVField(propInfo.GetValue(data, null)));
                        }
                    }
                }
                strBuilder
                    .Append(String.Join(";", csvRow.ToArray()))
                    .Append("\r\n");
            }


            return strBuilder.ToString();
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            AdaptPivotViewer ap = this.PivotViewer as AdaptPivotViewer;
            ap.showDataGrid();
            var datagrid = ap.Content as DataGrid;

            string data = ExportDataGrid(true, datagrid);
            SaveFileDialog sfd = new SaveFileDialog()
            {
                DefaultExt = "csv",
                Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
                FilterIndex = 1
            };
            if (sfd.ShowDialog() == true)
            {
                using (Stream stream = sfd.OpenFile())
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.Write(data);
                        writer.Close();
                    }
                    stream.Close();
                }
            }

        }

        private void Button_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        private void Button_MouseEnter(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        DateTime lastClick { get; set; }
        private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((DateTime.Now - lastClick).Ticks < 2500000)   
            {
                CreateStudentPopup((sender as DataGrid).SelectedItem);
            }
            lastClick = DateTime.Now;
        }


        private void CreateStudentPopup(object e)
        {
            var ms = e as MinimalStudent;
            bool exists = false;

            foreach (var c in this.wpPopups.Children)
            {
                if (c.GetType() == typeof(Border))
                {
                    if (((((c as Border).Child as StackPanel).Children[0] as HyperlinkButton).Tag as string).Equals(ms.MATRNR))
                    {
                        exists = true;
                        ((((c as Border).Child as StackPanel).Children[0] as HyperlinkButton).DataContext as Popup).IsOpen = true;
                    }
                }
            }

            if (!exists)
            {
                Popup popup = new Popup { HorizontalOffset = 200 + offset, VerticalOffset = 150 + offset };
                offset += 5;
                if (offset > 100)
                    offset = 0;
                popup.DataContext = ms; 
                Details details = new Details(popup);
                details.MouseLeftButtonUp += (snder, eargs) => { (snder as Details).Popup.IsOpen = false; (snder as Details).Popup.IsOpen = true; };
                PopupDragDrop.Attach(popup, details);
                var border = new Border() { BorderThickness = new System.Windows.Thickness(1, 1, 1, 1), BorderBrush = new SolidColorBrush(Colors.LightGray), Margin = new System.Windows.Thickness(0, 0, 20, 0) };
                var sp = new StackPanel() { Orientation = Orientation.Horizontal };
                var closebtn = new HyperlinkButton() { Content = "x", Margin = new System.Windows.Thickness(3, 0, 0, 0), Background = new SolidColorBrush(Colors.LightGray), Foreground = new SolidColorBrush(Colors.White) };
                var hlb = new HyperlinkButton() { Tag = ms.MATRNR, DataContext = popup, Content = ms.NACHNAME + ", " + ms.VORNAME, Foreground = ms.SexColor };
                hlb.Click += (sndr, eargs) => { if (popup.IsOpen) popup.IsOpen = false; else popup.IsOpen = true; };
                closebtn.Click += (snder, eargs) => { this.wpPopups.Children.Remove(border); popup.IsOpen = false; };

                sp.Children.Add(hlb);
                sp.Children.Add(closebtn);
                border.Child = sp;

                this.wpPopups.Children.Add(border);
                popup.IsOpen = true;
            }

        }

        private void Image_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
        {
            AdaptPivotViewer ap = this.PivotViewer as AdaptPivotViewer;
            UriBuilder builder = new UriBuilder(HtmlPage.Document.DocumentUri);
            builder.Query = "filter=" + ap.Filter;
            Clipboard.SetText(builder.Uri.ToString());
        }

        private Uri refreshUri { get; set; }
        private void Image_MouseLeftButtonUp_2(object sender, MouseButtonEventArgs e)
        {
            AdaptPivotViewer ap = this.PivotViewer as AdaptPivotViewer;
            UriBuilder builder = new UriBuilder(HtmlPage.Document.DocumentUri);
            builder.Query = "filter=" + ap.Filter;
            refreshUri = builder.Uri;
            //Vm.LoadMinimalStudents();
        }

        private bool isAno = false;
        private PivotViewerItemTemplate stdTemplate { get; set; }
        private GridLength oldWidth { get; set; }
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            AdaptPivotViewer ap = this.PivotViewer as AdaptPivotViewer;
            if (!isAno)
            {
                this.stdTemplate = ap.ItemTemplates[0];
                this.oldWidth = ap.DPWidth;
                ap.DPWidth = new GridLength(0);
                ap.ItemTemplates.Clear();
                ap.ItemTemplates.Add(this.LayoutRoot.Resources["AnonymTemplate"] as PivotViewerItemTemplate);

                isAno = true;
            }
            else
            {
                ap.ItemTemplates.Clear();
                ap.ItemTemplates.Add(stdTemplate);
                ap.DPWidth = this.oldWidth;

                isAno = false;
            }
        }

        private void Image_MouseLeftButtonUp_3(object sender, MouseButtonEventArgs e)
        {
            var c = new PrüfAnalysePopup(this.PivotViewer.ItemsSource);
            c.FilteringDone += (sendr, eargs) => { this.LayoutRoot.Children.Clear(); this.LayoutRoot.Children.Add(new PivotViewerGrid(c.ItemsSource)); };
            c.Show();
        }
    }
}
